package org.september.pisces.user.permission.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.september.pisces.user.permission.entity.SystemUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;


public class TokenSessionManager {

    private final static String tokenName = "user-token";
    
    private static Map<String,SystemUser> sessionUsers = new HashMap<>();
    
    public static synchronized HttpServletRequest getRequest() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert sra != null;
        return sra.getRequest();
    }

    public static String getToken() {
        HttpServletRequest request = getRequest();
        return request.getHeader(tokenName);
    }
    
    public static boolean isEnableToken() {
        HttpServletRequest request = getRequest();
        if(request.getHeader(tokenName)==null) {
        	return false;
        }else {
        	return true;
        }
    }
    
    public static String addSessionUser(SystemUser su) {
    	String token = UUID.randomUUID().toString();
    	sessionUsers.put(token, su);
    	return token;
    }
    
    public static void removeSessionUser() {
    	sessionUsers.remove(getToken());
    }

    public static SystemUser getSessionUser() {
    	return sessionUsers.get(getToken());
    }

}
